<template>
  <el-dialog title="上传图片" :visible.sync="visible">
    <div class="app-page">
      <el-upload
        ref="upload"
        class="avatar-uploader"
        action=""
        accept=".bmp, .gif, .jpg, .jpeg, .png, image/bmp, image/gif, image/jpg, image/jpeg, image/png"
        :show-file-list="false"
        :auto-upload="false"
        :on-change="handleChange"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon" />
      </el-upload>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button :loading="$loadingPlugin.success" type="primary" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { queryUploadGoodsTypeImage } from '@/api'
  import { imgBaseUrl } from '@/utils/config'

  export default {
    name: 'upIMG',
    data() {
      return {
        visible: false,
        row: {},
        imageUrl: '',
        file: null
      }
    },
    methods: {
      open(row) {
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          this.row = row
          if (row.imageName) {
            this.imageUrl = imgBaseUrl + row.imageName
          }
        })
      },
      handleChange(e) {
        this.imageUrl = URL.createObjectURL(e.raw)
        this.file = e.raw
      },
      async success() {
        await queryUploadGoodsTypeImage({
          gtId: this.row.gtId,
          files: this.file
        })
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '上传成功',
          type: 'success',
          duration: 2000
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.app-page {
  display: flex;
  justify-content: space-evenly;
  /deep/ .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
  }
}
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  line-height: 178px;
  color: #8c939d;
  text-align: center;
}
.avatar {
  display: block;
  width: 178px;
  height: 178px;
}
</style>
